package com.nasarius.bank.scorecard.web.controller.user;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.nasarius.bank.scorecard.dao.BankDetailsDAO;
import com.nasarius.bank.scorecard.dao.CommunicationFileDAO;
import com.nasarius.bank.scorecard.dao.CommunicationLogDAO;
import com.nasarius.bank.scorecard.domain.BankDetails;
import com.nasarius.bank.scorecard.domain.CommunicationFile;
import com.nasarius.bank.scorecard.domain.CommunicationLog;
import com.nasarius.bank.vo.CommunicationLogVO;

@Controller
public class CommunicationLogController {
	 /** Logger that is available to subclasses */
	 protected final Log LOG = LogFactory.getLog(getClass());
		@Autowired
		private CommunicationLogDAO communicationLogDAO;
		@Autowired		
		private BankDetailsDAO bankDetailsDAO;
		@Autowired		
		private CommunicationFileDAO communicationFileDAO;		
		@InitBinder
		protected void initBinder(ServletRequestDataBinder binder) {
				binder.registerCustomEditor(List.class,new CustomCollectionEditor(List.class));
				binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));				
		}		
		/**
		 * For every request for this controller, this will create a CommunicationLog
		 * instance for the form .
		 */
		@ModelAttribute
		public CommunicationLogVO newRequest(@RequestParam(required = false) String bankCode) {
			CommunicationLogVO communicationLogVO = new CommunicationLogVO();
			List<BankDetails> allBankDetails =bankDetailsDAO.selectAllAuthorizedBankDetails(SecurityContextHolder.getContext().getAuthentication().getName());
			communicationLogVO.setBankDetails(allBankDetails);
			communicationLogVO.setSelectedBankCode(bankCode);
			if(bankCode == null){
				communicationLogVO.setSelectedBankCode(allBankDetails.get(0).getBankcode());
			}	
			communicationLogVO.setCommunicationLog(communicationLogDAO.selectCommunicationLogByBankCode(communicationLogVO.getSelectedBankCode()));
			communicationLogVO.setCommunicationLogMessage("");	
			communicationLogVO.setSummaryLogMessage("");	
			return communicationLogVO;
		}
		   /**
	     * <p>Person form request.</p>
	     * 
	     * <p>Expected HTTP GET and request '/communicationlogdetails/view'.</p>
	     */
	    @RequestMapping(value="/communicationlogdetails/view", method=RequestMethod.GET)
	    public void form() {}
	    
		public void setBankDetailsDAO(BankDetailsDAO bankDetailsDAO) {
			this.bankDetailsDAO = bankDetailsDAO;
		}
	    /**
	     * @param communicationLogDAO
	     */
	    public void setCommunicationLogDAO(CommunicationLogDAO communicationLogDAO) {
			this.communicationLogDAO = communicationLogDAO;
		}
	    /**
	     * @param communicationLogDAO
	     */
	    public void setCommunicationFileDAO(CommunicationFileDAO communicationFileDAO) {
			this.communicationFileDAO = communicationFileDAO;
		}	    
	    @RequestMapping(value="/communicationlogdetails/update", method=RequestMethod.POST)
	    public String update(CommunicationLogVO communicationLogVO, Model model) {
	    	Integer commFileID = null;
    		if(communicationLogVO.getCommunicationFile() != null && 
    				StringUtils.isNotEmpty(communicationLogVO.getCommunicationFile().getOriginalFilename())){
    			CommunicationFile communicationFile = new CommunicationFile();
    			communicationFile.setCommunicationfile(communicationLogVO.getCommunicationFile().getBytes());
    			communicationFileDAO.insertcommunication_file(communicationFile);
    			commFileID = communicationFileDAO.countcommunication_file();
    		}
	    	if(communicationLogVO.getCommunicationLogMessage() != null){
	    		CommunicationLog communicationLog = new CommunicationLog();
	    		communicationLog.setBankcode(communicationLogVO.getSelectedBankCode());
	    		communicationLog.setCommunicationlog(communicationLogVO.getCommunicationLogMessage());
	    		communicationLog.setSummarylog(communicationLogVO.getSummaryLogMessage());
	    		communicationLog.setUser(SecurityContextHolder.getContext().getAuthentication().getName());
	    		if(communicationLogVO.getCommunicationFile() != null){
	    			communicationLog.setCommunicationfileid(commFileID);
	    			communicationLog.setCommunicationfilename(communicationLogVO.getCommunicationFile().getOriginalFilename());
	    		}
	    		communicationLogDAO.insertCommunicationLog(communicationLog);
	    	}
			return "redirect:/communicationlogdetails/view.html?bankCode="+ communicationLogVO.getSelectedBankCode(); 	    	
	    }
	    @RequestMapping(value="/communicationlogdetails/viewFile", method=RequestMethod.GET)	
	    public void viewFile(@RequestParam(required = false) String communicationfileid, 
	    		@RequestParam(required = false) String communicationfilename,
	    		HttpServletRequest r, HttpServletResponse response){
	    	ServletOutputStream out = null;
	    	CommunicationFile communicationFile = new CommunicationFile();
	    	System.out.println("communicationfileid"+communicationfileid);
	    	System.out.println("communicationfileid1"+Integer.parseInt(communicationfileid));
	    	communicationFile = communicationFileDAO.selectcommunication_fileByPrimaryKey(Integer.parseInt(communicationfileid));
	    	try {
				out = response.getOutputStream();
				MimetypesFileTypeMap mimeType = new MimetypesFileTypeMap();
	            response.setContentType(mimeType.getContentType(communicationfilename));
	            response.setHeader("Content-Disposition", "attachment; filename=\"" + communicationfilename + "\"");
	            out.write(communicationFile.getCommunicationfile());
	            out.flush();				
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
}
